package com.example.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.common.Constants;
import com.example.common.Result;
import com.example.common.enums.ResultCodeEnum;
import com.example.common.enums.RoleEnum;
import com.example.entity.Account;
import com.example.entity.Admin;
import com.example.entity.User;
import com.example.exception.CustomException;
import com.example.mapper.UserMapper;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务层方法
 */
@Service
public class UserService {

    @Resource
    private UserMapper userMapper;

    public void add(User user) {
        User dbUser = userMapper.selectByUsername(user.getUsername());
        if (ObjectUtil.isNotNull(dbUser)) {
            throw new CustomException(ResultCodeEnum.USER_EXIST_ERROR);
        }
        if (ObjectUtil.isEmpty(user.getPassword())) {
            user.setPassword(Constants.USER_DEFAULT_PASSWORD);
        }
        user.setRole(RoleEnum.USER.name());
        user.setAvatar(Constants.USER_DEFAULT_AVATAR);
        user.setId((int) ((Math.random() * 99) + 1));
        userMapper.insert(user);
    }

    public void updateById(User user) {
        userMapper.updateById(user);
    }

    public void deleteById(Integer id) {
        userMapper.deleteById(id);
    }

    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            userMapper.deleteById(id);
        }
    }

    public User selectById(Integer id) {
        return userMapper.selectById(id);
    }

    public List<User> selectAll(User user) {
        return userMapper.selectAll(user);
    }

    public PageInfo<User> selectPage(User user, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> list = userMapper.selectAll(user);
        return PageInfo.of(list);
    }


    public Result wxLogin(String code) {
        // 1. 向微信服务器发起请求，获取 openid 和 session_key
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String, Object> params = new HashMap<>();
        params.put("appid", "wxb5558b935468d5a0"); // 直接写死
        params.put("secret", "e6c677058997b37e823af1cd9cde492f"); // 直接写死
        params.put("js_code", code);
        params.put("grant_type", "authorization_code");

        String result = HttpUtil.get(url, params);
        JSONObject json = JSONUtil.parseObj(result);

        // 2. 判断是否返回错误
        if (json.containsKey("errcode")) {
            return Result.error(json.getStr("errmsg"));
        }

        // 3. 提取 openid 和 session_key
        String openid = json.getStr("openid");
        String sessionKey = json.getStr("session_key");


        //4. 将openid和session_key保存到数据库中 以及用户信息
        User user = userMapper.selectByOpenid(openid);


        if (user == null) {
            user = new User();
            // 32位字母数字
            user.setId((int) ((Math.random() * 99) + 1));
            user.setOpenid(openid);
            user.setUsername("微信用户");
            user.setAvatar("https://q0.itc.cn/q_70/images03/20250129/d3e537d467a040829764e8598e33e5e1.png");
            user.setRole(RoleEnum.USER.name());
            user.setPassword(Constants.USER_DEFAULT_PASSWORD);
            user.setScore(0);
            userMapper.insert(user);
        }

        //5.生成token
        String token = TokenUtils.createToken(openid, sessionKey);

        //6.返回结果
        Map<String, Object> data = new HashMap<>();
        data.put("token", token);
        data.put("user", user);
        return Result.success(data);
    }

    public Account login(Account account) {
        User dbUser = userMapper.selectByUsername(account.getUsername());
        if (ObjectUtil.isNull(dbUser)) {
            throw new CustomException(ResultCodeEnum.USER_NOT_EXIST_ERROR);
        }
        if (!dbUser.getPassword().equals(account.getPassword())) {
            throw new CustomException(ResultCodeEnum.USER_ACCOUNT_ERROR);
        }
        // 生成token
        String token = TokenUtils.createToken(dbUser.getId() + "-" + dbUser.getRole(), dbUser.getPassword());
        dbUser.setToken(token);
        return dbUser;
    }

    public void register(Account account) {
        User user = new User();
        BeanUtils.copyProperties(account, user);
        add(user);
    }
}
